﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
//using HeSeHus.Model;
using HeSeHus.Controller;
using HeSeHus.Interface;
using Microsoft.Win32;
using System.IO;
using HeSeHus.Properties;
using System.ComponentModel;
using System.Windows.Threading;


namespace HeSeHus
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SystemController controller;
        //Dictionary<Product, PropertyCollection> objectDic;

        public MainWindow()
        {
            #region Settings
            
            StreamReader sr = new StreamReader("ConfigFiles/ConStrings.txt");
           
            string line = sr.ReadLine();
            string[] række = line.Split(';');
            Settings.Default["NativeDatabase"] = række[0];
            Settings.Default["NativeCatalog"] = række[1];
            Settings.Default["NativeUser"] = række[2];
            Settings.Default["NativePassword"] = række[3];
            Settings.Default.Save();

            string line1 = sr.ReadLine();
            string[] række1 = line1.Split(';');
            Settings.Default["ProdDatabase"] = række1[0];
            Settings.Default["ProdCatalog"] = række1[1];
            Settings.Default["ProdUser"] = række1[2];
            Settings.Default["ProdPassword"] = række1[3];
            Settings.Default.Save();


            Settings.Default["NativeConString"] = "server=" + Settings.Default["NativeDatabase"] + "; initial catalog=" + Settings.Default["NativeCatalog"] + "; user=" + Settings.Default["NativeUser"] + "; password=" + Settings.Default["NativePassword"] + ";";
            Settings.Default["ProductionConString"] = "server=" + Settings.Default["ProdDatabase"] + "; initial catalog=" + Settings.Default["ProdCatalog"] + "; user=" + Settings.Default["ProdUser"] + "; password=" + Settings.Default["ProdPassword"] + ";";
            
            
           
            sr.Close();

            #endregion

            ImgNativeStatus = null;

            controller = new SystemController();

            InitializeComponent();

            #region Iteration til at tilføje .xml filer til filer combobox
            foreach (var item in Directory.GetFiles(Directory.GetCurrentDirectory() + "/ConfigFiles/","*.xml"))
            {
                if (item.Contains("GENERATED"))
                {
                    
                    ribbonFilesCbo.Items.Add(Path.GetFileName(item).ToString());
                }
                

            } 
            #endregion

            #region Progressbar 
            statusBar.Visibility = Visibility.Collapsed;
            
            #endregion

            #region Database status check (Ping)
            ImageSource[] temp = RefreshStatus();
            ImgNativeStatus.Source = temp[0];
            imgProductionStatus.Source = temp[1]; 
            #endregion
        }


        #region Indlæs/Parse/Importer filer valgt på disk (Event)
        string[] fileArray;
        private void RibbonButton_Click_2(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = ".xml |*.xml";
            ofd.Multiselect = true;
            ofd.ShowDialog();

            fileArray = ofd.FileNames;

            BackgroundWorker xmlBg = new BackgroundWorker();
            xmlBg.DoWork += xmlBg_DoWork;
            xmlBg.RunWorkerCompleted += xmlBg_RunWorkerCompleted;
            xmlBg.RunWorkerAsync();
            
            statusBar.IsIndeterminate = true;
            statusBar.Visibility = Visibility.Visible;
            lblStatusText.Content = "Importerer XML data...";
        }

        void xmlBg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            statusBar.IsIndeterminate = false;
            statusBar.Visibility = Visibility.Collapsed;
            lblStatusText.Content = "Færdig!";
        }

        public delegate void dgvViewDelegate();
        public delegate void tabBerigelse();
        public delegate void tabPræsentation();
        void xmlBg_DoWork(object sender, DoWorkEventArgs e)
        {
            //objectDic = 
            controller.ParseXML(fileArray);
            dgvView.Dispatcher.Invoke(DispatcherPriority.Normal, new dgvViewDelegate(SetDgvView));
            ribbonTabBerigelse.Dispatcher.Invoke(DispatcherPriority.Normal, new tabBerigelse(UnlockBerigelseTab));
            ribbonTabPræsentation.Dispatcher.Invoke(DispatcherPriority.Normal, new tabPræsentation(UnlockPræsentationsTab));
        }

        public void SetDgvView()
        {
            dgvView.ItemsSource = null;
            dgvView.ItemsSource = controller.ReturnDictionary.Keys;
        }
        public void UnlockBerigelseTab()
        {
            ribbonTabBerigelse.IsEnabled = true;
        }
        public void UnlockPræsentationsTab()
        {
            ribbonTabPræsentation.IsEnabled = true;
        }
        #endregion

        #region ConnectionSettings Windows Loader
        private void RibbonButton_Click_1(object sender, RoutedEventArgs e)
        {
            connectionString cs = new connectionString(true);
            cs.ShowDialog();
        }

        private void RibbonButton_Click_5(object sender, RoutedEventArgs e)
        {
            connectionString cs = new connectionString(false);
            cs.ShowDialog();
        } 
        #endregion

        #region TODO Events Credentials & Statistics
        private void RibbonButton_Click_6(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Credentials settings PROD");
        }

        private void RibbonButton_Click_7(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Statistics show PROD");
        }

        private void RibbonButton_Click_3(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Credentials settings");
        }

        private void RibbonButton_Click_4(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Statistics show");
        } 
        #endregion

        #region Event til visning af Properties på et produkt
        private void dgvView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Tjek for intet valg
            if (dgvView.SelectedItem != null)
            {
                dgvProperties.ItemsSource = null;
                dgvProperties.ItemsSource = controller.ReturnDictionary[(IMProduct)dgvView.SelectedItem];
            }
            else
            {

            }
            
        } 
        #endregion

        #region Upload til Produktions database
        private void RibbonButton_Click_8(object sender, RoutedEventArgs e)
        {
            BackgroundWorker databaseWorker = new BackgroundWorker();
            databaseWorker.DoWork += databaseWorker_DoWork;
            databaseWorker.RunWorkerCompleted += databaseWorker_RunWorkerCompleted;
            databaseWorker.RunWorkerAsync();

            statusBar.IsIndeterminate = true;
            statusBar.Visibility = Visibility.Visible;
            lblStatusText.Content = "Uploader data...";
            
        }

        void databaseWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            statusBar.IsIndeterminate = false;
            statusBar.Visibility = Visibility.Collapsed;
            lblStatusText.Content = "Færdig!";
        }

        void databaseWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            controller.DBCaller(controller.ReturnDictionary, Settings.Default["ProductionConString"].ToString(), true);
        } 
        #endregion

        #region Rens Produktions Database
        private void RibbonButton_Click_9(object sender, RoutedEventArgs e)
        {
            controller.DBCallerClean(Settings.Default["ProductionConString"].ToString(), true);
        } 
        #endregion

        #region Rens Native Database
        private void RibbonButton_Click_11(object sender, RoutedEventArgs e)
        {
            controller.DBCallerClean(Settings.Default["NativeConString"].ToString(), true);
        } 
        #endregion

        #region 0-Kørsel
        private void RibbonButton_Click_10(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Denne handling vil slette de eksisterende data i databaserne(" + Settings.Default["ProdDatabase"] + " og " + Settings.Default["NativeDatabase"] + ")\r\n\r\nEr du sikker?", "Nul kørsel", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                controller.DBCallerClean(Settings.Default["NativeConString"].ToString(), true);
                controller.DBCallerClean(Settings.Default["ProductionConString"].ToString(), false);
                controller.DBCaller(controller.ReturnDictionary, Settings.Default["NativeConString"].ToString(), true);
                controller.DBCaller(controller.ReturnDictionary, Settings.Default["ProductionConString"].ToString(), false);
            }

        } 
        #endregion

        #region Refresh Database / Ping Metoder
        private void RibbonButton_Click_12(object sender, RoutedEventArgs e)
        {
            BackgroundWorker bg = new BackgroundWorker();
            bg.DoWork += bg_DoWork;
            bg.RunWorkerCompleted += bg_RunWorkerCompleted;
            bg.RunWorkerAsync();

            statusBar.IsIndeterminate = true;
            statusBar.Visibility = Visibility.Visible;
            lblStatusText.Content = "Forbinder til database...";
            
            
        }

        void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            statusBar.Visibility = Visibility.Collapsed;
            statusBar.IsIndeterminate = false;
            lblStatusText.Content = "Færdig!";
        }

       
        public delegate void imgNative();
        public delegate void imgProduction();
        ImageSource[] temp;
        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            temp = RefreshStatus();
            
            ImgNativeStatus.Dispatcher.Invoke(DispatcherPriority.Normal, new imgNative(imgNativeSet));
            imgProductionStatus.Dispatcher.Invoke(DispatcherPriority.Normal, new imgProduction(imgProdSet));
        }

        public void imgNativeSet()
        {
            ImgNativeStatus.Source = temp[0];
        }
        public void imgProdSet()
        {
            imgProductionStatus.Source = temp[1];
        }
     

        public ImageSource[] RefreshStatus()
        {
            bool[] isNativeArray = new bool[] { true, false };
            string[] connectionStringArray = new string[] { Settings.Default["NativeConString"].ToString(), Settings.Default["ProductionConString"].ToString() };
            string[] ipAdresseArray = new string[] { Settings.Default["NativeDatabase"].ToString(), Settings.Default["ProdDatabase"].ToString() };
            
            return controller.PingDatabase(ipAdresseArray, 1433, isNativeArray, connectionStringArray);
        }

        

        

        
        #endregion

        #region Indlæs/Parse/Importer filer på std. sti
        private void RibbonButton_Click_13(object sender, RoutedEventArgs e)
        {
            fileArray = new string[ribbonFilesCbo.Items.Count];
            for (int i = 0; i < ribbonFilesCbo.Items.Count; i++)
            {
                fileArray[i] = ribbonFilesCbo.Items[i].ToString();
            }
            BackgroundWorker xmlBg = new BackgroundWorker();
            xmlBg.DoWork += xmlBg_DoWork;
            xmlBg.RunWorkerCompleted += xmlBg_RunWorkerCompleted;
            xmlBg.RunWorkerAsync();

            statusBar.IsIndeterminate = true;
            statusBar.Visibility = Visibility.Visible;
            lblStatusText.Content = "Importerer XML data...";
        } 
        #endregion

        #region Tilføj ny Property og opdater GUI
        
        private void RibbonButton_Click_14(object sender, RoutedEventArgs e)
        {
            //Åbner en "tilføj Property" dialog og sender et Product Interface samt en  reference - (ikke en kopi) -
            //til this.controller, så der arbejdes i den eksisterende Model.
           
            TilføjProperty property = new TilføjProperty((IMProduct)dgvView.SelectedItem, ref controller);
            property.ShowDialog();

            dgvProperties.ItemsSource = null;
            dgvProperties.ItemsSource = controller.ReturnDictionary[(IMProduct)dgvView.SelectedItem];

            //dgvView.ItemsSource = null;
            //dgvView.ItemsSource = controller.ReturnDictionary.Keys;


        }
        #endregion



    }
}
